package com.naughty.shopapi.utils;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
    /**
     * 文件名后缀前添加一个时间戳
     */
    public static String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }

    /**
     * 获取当前系统路径
     */
    public static String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyy-MM");  //设置时间格式
        String nowTimeDir = sDateFormate.format(new Date());
        File upload = new File(path.getAbsolutePath(), "static/images/" + nowTimeDir);
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }
}
